package com.ruoyi.wifiauth.service.impl;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.wifiauth.domain.WifiAuthLog;
import com.ruoyi.wifiauth.mapper.WifiAuthLogMapper;
import com.ruoyi.wifiauth.service.IWifiAuthService;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.redis.service.RedisService;

@Service
public class WifiAuthServiceImpl implements IWifiAuthService {

    private static final String KEY_PREFIX = "wifi:session:";

    @Autowired
    private WifiAuthLogMapper wifiAuthLogMapper;

    @Autowired
    private RedisService redisService;

    @Value("${auth.session.ttl-seconds:600}")
    private long sessionTtlSeconds;

    @Override
    @Transactional
    public String createAuthSession(String deviceId, String scene, String clientIp) {
        String sessionId = UUID.randomUUID().toString().replace("-", "");
        WifiAuthLog log = new WifiAuthLog();
        log.setSessionId(sessionId);
        log.setDeviceId(deviceId);
        log.setStatus(0); // 处理中
        log.setErrorMsg(null);
        log.setCreateTime(DateUtils.getNowDate());
        wifiAuthLogMapper.insert(log);
        // 缓存初始化状态，便于快速查询 & TTL
        redisService.setCacheObject(KEY_PREFIX + sessionId, 0, sessionTtlSeconds, TimeUnit.SECONDS);
        return sessionId;
    }

    @Override
    @Transactional
    public boolean recordWeChatAuth(String sessionId, String openId, String unionId) {
        WifiAuthLog existed = wifiAuthLogMapper.selectBySessionId(sessionId);
        if (existed == null) {
            return false;
        }
        WifiAuthLog log = new WifiAuthLog();
        log.setSessionId(sessionId);
        log.setOpenid(openId);
        log.setStatus(1); // 成功
        log.setUpdateTime(DateUtils.getNowDate());
        boolean ok = wifiAuthLogMapper.updateBySessionId(log) > 0;
        if (ok) {
            redisService.setCacheObject(KEY_PREFIX + sessionId, 1, sessionTtlSeconds, TimeUnit.SECONDS);
        }
        return ok;
    }

    @Override
    public WifiAuthLog getStatus(String sessionId) {
        Integer cache = redisService.getCacheObject(KEY_PREFIX + sessionId);
        if (cache != null) {
            WifiAuthLog temp = new WifiAuthLog();
            temp.setSessionId(sessionId);
            temp.setStatus(cache);
            return temp;
        }
        return wifiAuthLogMapper.selectBySessionId(sessionId);
    }
} 